package system;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;

import system.StreamUtil;
import system.IO;

public class update {

	public static final int VERSION = 15021901;
	private static boolean UPDATE = false;

	public static void main(String[] args) throws IOException, InterruptedException {

		System.out.print("　　　　　　　　　《 檢查更新檔案中... 》");
		System.out.println("版本: "+VERSION);
		File file = new File("./lineage-list.txt");
		if(!file.isFile()){
			System.out.println("找不到必要檔案，請確認安裝位置是否正確。");
			Thread.sleep(5000);
			System.exit(0);
		}
		UPDATE = checkVer();
		if(UPDATE){
			System.out.print("自動更新檔案中...");
			try {
				URL url = new URL("https://dl.dropboxusercontent.com/u/61561180/NewHigo.jar");
				InputStream src = url.openStream();
				OutputStream dest = new FileOutputStream("./NewHigo.jar");
				IO.dump(src, dest);
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				}
				System.out.println("完成!!");
			}catch(Exception e){
				e.printStackTrace();
				Thread.sleep(100000);
				System.exit(0);
			}
		}else{
			System.out.println("最新版本，無須更新!!");
		}
		setFile();
		@SuppressWarnings("unused")
		Process pro = null;
		try{
			Runtime r =Runtime.getRuntime();
			pro = r.exec("cmd /c @start lib/bin/java -cp NewHigo.jar; server.system.comURL");
		}catch (IOException e) {
			System.exit(0);
		}
	}

	private static boolean checkVer(){
		InputStream src = null;
		try {
			URL url = new URL("https://dl.dropboxusercontent.com/u/61561180/Login_Version.ini");
			src = url.openStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(src)); 
			Integer version =Integer.valueOf(br.readLine());
			if(version !=null){
				return ( version != VERSION );
			}
		} catch (Exception e) {
		}finally{
			StreamUtil.close(src);
		}
		return false;
	}

	private static void setFile(){
		BufferedWriter out = null;
		try {
			out = new BufferedWriter(new FileWriter("./LineageVesion.ini", false));
			if(out !=null){
				out.write(String.valueOf(UPDATE));
				out.flush();
			}
		}catch(Exception e){
		}finally{
			StreamUtil.close(out);
		}
	}
}
